<?php

	global $TIMECARD_CONFIG;
	$m = $AppUI->checkFileName(dPgetParam( $_GET, 'm', getReadableModule() ));
	$denyEdit = getDenyEdit( $m );
	if ($denyEdit) {
		$AppUI->setMsg('Access denied', UI_MSG_ERROR);
		$AppUI->redirect();
	}

	//grab hours per day from config
	$min_hours_day = $AppUI->cfg['daily_working_hours'];
	$can_edit_other_timesheets = $TIMECARD_CONFIG['minimum_edit_level']>=$AppUI->user_type;
	$show_other_worksheets = $TIMECARD_CONFIG['minimum_see_level']>=$AppUI->user_type;
	$show_possible_hours_worked = $TIMECARD_CONFIG['show_possible_hours_worked'];
	//print "<pre>";
	//print_r($AppUI);
	//print "</pre>";

	//compute hours/week from config
	$min_hours_week = count(explode(",",dPgetConfig("cal_working_days"))) * $min_hours_day;

	// get date format
	$df = $AppUI->getPref('SHDATEFORMAT');

	if (isset( $_GET['user_id'] )) {
		$sql = "SELECT user_company FROM users WHERE user_id = ".$_GET['user_id'] ;
		$company_id = db_loadResult( $sql );
		if(getDenyRead( "companies", $company_id )){
			$AppUI->setMsg('Access denied', UI_MSG_ERROR);
			$AppUI->redirect();
		}
		$AppUI->setState( 'TimecardSelectedUser', $_GET['user_id'] );
	}
	$user_id = $AppUI->getState( 'TimecardSelectedUser' ) ? $AppUI->getState( 'TimecardSelectedUser' ) : $AppUI->user_id;

	$AppUI->savePlace();

	if (isset( $_GET['start_date'] )) {
		$AppUI->setState( 'TimecardStartDate', $_GET['start_date'] );
	}
	$start_day = new CDate( $AppUI->getState( 'TimecardStartDate' ) ? $AppUI->getState( 'TimecardStartDate' ) : NULL);

	//set the time to noon to combat a php date() function bug that was adding an hour.
	$date = $start_day->format('%Y-%m-%d').' 12:00:00';
	$start_day -> setDate($date, DATE_FORMAT_ISO);

	$today_weekday = $start_day -> getDayOfWeek();

	//roll back to the first day of that week, regardless of what day was specified
	$rollover_day = '0';
	$new_start_offset = $rollover_day - $today_weekday;
	$start_day -> addDays($new_start_offset);

	//last day of that week, add 6 days
	$end_day = new CDate ();
	$end_day -> copy($start_day);
	$end_day -> addDays(6);

	//date of the first day of the previous week.
	$prev_date = new CDate ();
	$prev_date -> copy($start_day);
	$prev_date -> addDays(-7);

	//date of the first day of the next week.
	$next_date = new CDate ();
	$next_date -> copy($start_day);
	$next_date -> addDays(7);

	//***MOD 20050525 pedroa $is_my_timesheet = $user_id == $AppUI->user_id;
	$is_my_timesheet = ($user_id == $AppUI->user_id || $can_edit_other_timesheets);

	?>
	<script>
		function viewLog(id) {
			go('index.php?m=tasks&a=view&task_id='+id);
		}

		function editLog(id) {
			go('index.php?m=timecard&tab=1&tid='+id);
		}

		function deleteLog(id, name, day) {
			if (confirm('Are you sure you want to delete task log\n[ '+name+' ]\ncreated on '+day+'?')) {
				var f = document.DelLog;
				f.task_log_id.value = id;
				f.submit();
			}
		}
	</script>
	<form name="user_select" method="get">
	<input type="hidden" name="m" value="timecard">
	<input type="hidden" name="tab" value="0">
	<input type="hidden" name="start_date" value="<?php echo $start_day->getDate();?>">
	<table align="center" class="infopanel" width="100%" style="padding: 4px">
		<tr>
			<td><a href="?m=timecard&user_id=<?php echo $user_id;?>&start_date=<?php echo urlencode($prev_date->getDate()) ;?>"><img src="images/prev.gif" title="<?php echo $AppUI->_( 'Previous' );?>"></a></td>
			<td nowrap="nowrap"><b>
			<?php
				echo $start_day -> getDayName(false). ' ' .$start_day->format( $df ).' - '.
						$end_day -> getDayName(false). ' ' .$end_day->format( $df );
			?>
			</b></td>
			<td><a href="?m=timecard&user_id=<?php echo $user_id;?>&start_date=<?php echo urlencode($next_date->getDate()) ;?>"><img src="images/next.gif" title="<?php echo $AppUI->_( 'Next' );?>"></a></td>
	<?php
		if ($show_other_worksheets) {
	?>
			<td align="right" width="100%">
				<select name="user_id" onChange="document.user_select.submit();">
		<?php
			$sql = 'SELECT user_id,contact_first_name,contact_last_name
					FROM users
					INNER JOIN contacts on contact_id = user_contact
					WHERE users.user_id <> '.$AppUI->user_id.' AND users.user_id <> 1
					ORDER BY contact_first_name, contact_last_name';

			$result = db_loadList($sql);
			echo '<option value="'.$AppUI->user_id.'">My Time Card</option>';
			foreach ($result as $user) {
				echo '<option value="'.$user['user_id'].'" '.($user['user_id']==$user_id ? 'selected':'').'>'.
						$user['contact_first_name'].' '.$user['contact_last_name'].'</option>';
			}
		?>
				</select>
			</td>
	<?php
		}
	?>
		</tr>
	</table>
	<table id="idCardList" width="100%" border="0" cellpadding="3" cellspacing="0" class="list">
		<thead>
		<tr>
			<th nowrap="nowrap" width="1%" colspan="2"><?php echo $AppUI->_('Task Name'); ?></th>
			<th width="85%"><?php echo $AppUI->_('Log Entry'); ?></th>
			<th width="14%"><?php echo $AppUI->_('Hours'); ?></th>
		</tr>
		</thead>
		<!--tbody class="scrollContent"-->
	<?php
	//set the time the beginning of the first day and end of the last day.
	$date = $start_day->format("%Y-%m-%d")." 00:00:00";
	$start_day -> setDate($date, DATE_FORMAT_ISO);
	$date = $end_day->format("%Y-%m-%d")." 23:59:59";
	$end_day -> setDate($date, DATE_FORMAT_ISO);

	$sql = 'SELECT task_log.*, tasks.task_id, projects.project_id, projects.project_name
		FROM
			task_log
			LEFT JOIN tasks on task_log.task_log_task = tasks.task_id
			LEFT JOIN projects on  tasks.task_project = projects.project_id
		WHERE '
		.' task_log_creator = '.$user_id.' AND'
		.' task_log_date >= "'.$start_day->format( FMT_DATETIME_MYSQL ).'" AND '
		.' task_log_date <= "'.$end_day->format( FMT_DATETIME_MYSQL ).'" '
		.' ORDER BY projects.project_name, task_log_date';

	$result = db_loadList($sql);
	$date = $start_day->format("%Y-%m-%d")." 12:00:00";
	$start_day -> setDate($date, DATE_FORMAT_ISO);

	$rowspan_count=0;
	$total_hours_daily=0;
	$total_hours_weekly=0;
	$dow=0;
	$last_day = new CDate();
	$last_day -> copy($start_day);
	$no_results = true;
	$first = 1;

	for ($dow = 0; $dow < 7; $dow++) {
		$dmsg = $last_day->getDayName(false).' '.$last_day->format($df);
		writeDayLine($last_day,$df,$AppUI->_('Add Task Log'),$is_my_timesheet,$user_id);

		$ntasks = 0;
		$pname = '';
		foreach ($result as $task) {
			$task_date = new CDate( $task['task_log_date'] );
			$task_dow = $task_date->getDayOfWeek();

			if ($task_dow == $dow) {
				$ntasks++;
				$total_hours_daily += $task['task_log_hours'];
				if ($pname != $task['project_name']) {
					$pname = $task['project_name'];
					echo '<tr class="second" onclick="viewProject('.$task['project_id'].')">'.
							'<td colspan="100%" style="padding-left: 24px"><b>'.$pname.'</b></td></tr>';
				}
				?>
				<tr class="second">
					<td nowrap="nowrap" style="padding-left: 24px" valign="top">
					<? if ($task['task_log_creator']==$AppUI->user_id || $can_edit_other_timesheets) { ?>
						<img class="clickable" src="images/edit_log.gif" title="Edit"
							onclick="editLog(<?=$task['task_log_id']?>)"/>
						<img class="clickable" src="images/delete_log.gif" title="Delete"
							onclick="deleteLog(<?=$task['task_log_id']?>,
										'<?=addslashes($task['task_log_name'])?>','<?=$dmsg?>')"/>
					<? } else { ?>
						<img src="images/noedit_log.gif"/>
						<img src="images/nodel_log.gif"/>
					<? } ?>
					</td>
					<td valign="top" nowrap="nowrap" onclick="viewLog(<?=$task['task_id']?>)" title="View detail">
						<?=$task['task_log_name']?>
					</td>
					<td valign="top" onclick="viewLog(<?=$task['task_id']?>)">
						<?=str_replace("\n", '<br/>', $task['task_log_description'])?>
					</td>
					<td align="right" valign="top" onclick="viewLog(<?=$task['task_id']?>)">
						<?=sprintf('%.2f', $task['task_log_hours'])?>
					</td>
				</tr>
				<?php
			}
		}

		if ($ntasks == 0) {
			echo '<tr class="padding"><td colspan="2">&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
		}

		writeDayTotal($AppUI->_('Total'),$last_day->isWorkingDay(),$total_hours_daily,$min_hours_day, $show_possible_hours_worked);
		$total_hours_weekly += $total_hours_daily;
		$total_hours_daily = 0;
		$last_day->addDays(1);
		$date = $last_day->format("%Y-%m-%d")." 12:00:00";
		$last_day -> setDate($date, DATE_FORMAT_ISO);
	}

//	echo '</tbody>';
	echo '<tr><th valign="top" colspan="100%">'.
			$AppUI->_('For the week of').' '.
			$start_day->getDayName(false).' '.$start_day->format( $df ).' - '.
			$end_day->getDayName(false).' '.$end_day->format( $df ).'</b></th></tr>';;
	echo '<tr><td colspan="3" align="right"><b>'.$AppUI->_('Total Hours').'</b></td><td align="right">';
	if ($show_possible_hours_worked && $total_hours_weekly<$min_hours_week) {
		echo '<b><span class="subHours">'.($min_hours_week-$total_hours_weekly).'</span></b>';
	}
	echo '<b>'.sprintf('%.2f', $total_hours_weekly).'</b>';
	echo '</td></tr>';
	?>
	</table>
	</form>
	<form name="DelLog" action="" method="post">
	<input type="hidden" name="m" value="timecard">
	<input type="hidden" name="tab" value="0">
	<input type="hidden" name="dosql" value="do_updatetasklog">
	<input type="hidden" name="del" value="1">
	<input type="hidden" name="task_log_id" value="0">
	</form>
	<script>
		Table('idCardList').setSelectiveHover(1, ['first', 'second']);
	</script>
<?php
function writeDayLine($day,$format,$task_string,$show_add,$userid)
{
	$day_name = $day->getDayName(false);
	echo '<tr><td nowrap="nowrap" valign="middle" colspan="100%">';
	echo $show_add ?
		'<a href="?m=timecard&tab=1&userid='.$userid.'&date='.urlencode($day->getDate()).'"><img src="images/add_log.gif" border="0" title="'.$task_string.'"/></a>' :
		'<img src="images/task_grp.gif"/>';
	echo '&nbsp;&nbsp;<b>'.$day_name.'</b> '.$day->format( $format ).'</td>';
	echo '</tr>';
}

function writeDayTotal($total_string,$workday,$total_hours,$hours_per_day, $show_possible_hours_worked)
{
	echo '<tr class="summary"><td colspan="3" align="right"><b>'.$total_string.'</b></td>';
	echo '<td align="right">';
	if ($show_possible_hours_worked && $total_hours<$hours_per_day && $workday){
		echo '<b><span class="subHours">'.($hours_per_day-$total_hours).'</span></b>';
	}
	echo '<b>'.sprintf('%.2f', $total_hours).'</b>';
	echo '</td></tr>';
	echo '<tr class="padding"><td colspan="100%"><img src="images/shim.gif" height="1" width="100%"></td></tr>';
}

?>
